﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TrainStation.Tracks;
using TrainStation.TrainModules;

namespace TrainStation
{
    public delegate void StateChangedEventHandler(object sender, EventArgs e);

    public class Train
    {
        public double CurrentSpeed { get; set; }
        public double RequestedSpeed { get; set; }
        public double Acceleration { get; set; }
        public double MaxSpeed { get { return Wagons.Max(p => p.MaxSpeed); } }

        public event StateChangedEventHandler StateChanged;
        protected virtual void OnChanged( StateChangedEventArgs e )
        {
            if (StateChanged != null)
            {
                StateChanged(this, e);
            }
        }

        public ITrack CurrentTrack { get; set; }
        private TrainState currentState;
        public TrainState CurrentState 
        {
            get { return currentState; }
            set 
            {
                var previousState = currentState;
                currentState = value;
                OnChanged(new StateChangedEventArgs(previousState, currentState));
            }
        }

        public int TrainLength 
        {
            get { return 8 + ( Wagons.Sum(p=>p.Length)); }
        }

        /// <summary>
        /// Position relative to CurrentTrack.Length
        /// </summary>
        public double Position { get; set; }

        public List<ITrainWagon> Wagons { get; set; }

        public Train()
        {
            Wagons = new List<ITrainWagon>();
            CurrentSpeed = 0;
            RequestedSpeed = 0;
            Acceleration = 7;

            CurrentState = TrainState.Stopped;
        }

        public void AddWagon(ITrainWagon wagon)
        {
            Wagons.Add(wagon);
        }

        public void Go()
        {
            this.RequestedSpeed = this.MaxSpeed;
            this.CurrentState = TrainState.Running;
        }

        public void Stop()
        {
            CurrentState = TrainState.Stopped;
        }
    }
}
